<template>
	<cl-drawer
		ref="drawer"
		:props="{
			title: '添加部门月目标',
			size: '75%'
		}"
		show-confirm
		confirm-text="提交"
		@close="reset"
		@confirm="submit"
		:saving="saving"
	>
		<el-form ref="form" label-position="top" :disabled="saving" :model="form" :rules="rules">
			<el-form-item label="事业部" prop="biz_id">
				<el-card shadow="never" body-style="padding-bottom:10px">
					<el-radio-group v-model="form.biz_id" @change="changeBiz" style="width: 100%">
						<el-row>
							<el-col
								:lg="4"
								:md="6"
								:sm="12"
								class="mb-1"
								v-for="item in business"
								:key="item.biz_id"
							>
								<el-radio :label="item.biz_id">
									{{ item.biz_name }}
								</el-radio>
							</el-col>
						</el-row>
					</el-radio-group>
				</el-card>
			</el-form-item>
			<el-form-item label="分公司" prop="company_ids">
				<el-card shadow="never" body-style="padding-bottom:10px">
					<el-checkbox-group v-model="form.company_ids" @change="changeCom">
						<el-row>
							<el-col
								:lg="4"
								:md="6"
								:sm="12"
								class="mb-1"
								v-for="item in bizRefData.company"
								:key="item.company_id"
							>
								<el-checkbox :label="item.company_id">
									{{ item.company_name }}
								</el-checkbox>
							</el-col>
						</el-row>
					</el-checkbox-group>
				</el-card>
			</el-form-item>
			<el-form-item label="部门" prop="dept_ids">
				<el-card shadow="never" body-style="padding-bottom:10px">
					<el-checkbox-group v-model="form.dept_ids" @change="setTargetList">
						<el-row>
							<el-col
								:lg="4"
								:md="6"
								:sm="12"
								class="mb-1"
								v-for="item in deptList"
								:key="item.dept_id"
							>
								<el-checkbox :label="item.dept_id">
									{{ item.dept_name }}
								</el-checkbox>
							</el-col>
						</el-row>
					</el-checkbox-group>
				</el-card>
			</el-form-item>
			<el-form-item label="品牌" prop="bra_ids">
				<el-card shadow="never" body-style="padding-bottom:10px">
					<el-checkbox-group v-model="form.bra_ids" @change="setTargetList">
						<el-row>
							<el-col
								:lg="4"
								:md="6"
								:sm="12"
								class="mb-1"
								v-for="item in bizRefData.brand"
								:key="item.bra_id"
							>
								<el-checkbox :label="item.bra_id">
									{{ item.bra_name }}
								</el-checkbox>
							</el-col>
						</el-row>
					</el-checkbox-group>
				</el-card>
			</el-form-item>
			<el-form-item label="月份" prop="create_date">
				<el-card shadow="never">
					<cl-date-picker
						v-model="form.create_date"
						@change="setTargetList"
						placeholder="请选择月份"
						type="month"
						value-format="yyyy-MM"
						style="width: 200px"
					/>
				</el-card>
			</el-form-item>
			<el-form-item label="目标计划">
				<el-card shadow="never">
					<el-table :data="form.target_list" border>
						<cl-empty slot="empty" />
						<el-table-column label="事业部" prop="biz_name" align="center" />
						<el-table-column label="分公司" prop="company_name" align="center" />
						<el-table-column label="部门" prop="dept_name" align="center" />
						<el-table-column label="品牌" prop="bra_name" align="center" />
						<el-table-column
							label="加微数(月)"
							prop="vorder_total"
							align="center"
							width="100"
						>
							<template slot-scope="{ row, $index }">
								<el-form-item
									:prop="`target_list.${$index}.vorder_total`"
									:rules="rules.vorder_total"
									:show-message="false"
									:inline-message="true"
								>
									<el-input
										v-model.number="row.vorder_total"
										@input="quantityTotalChange(row)"
									/>
								</el-form-item>
							</template>
						</el-table-column>
						<el-table-column
							label="加微数(日)"
							prop="vorder_day"
							align="center"
							width="100"
						>
							<template slot-scope="{ row, $index }">
								<el-form-item
									:prop="`target_list.${$index}.vorder_day`"
									:rules="rules.vorder_day"
									:show-message="false"
									:inline-message="true"
								>
									<el-input v-model.number="row.vorder_day" />
								</el-form-item>
							</template>
						</el-table-column>
						<el-table-column
							label="新客定金数(月)"
							prop="old_new_vorder_total"
							width="130"
							align="center"
						>
							<template slot-scope="{ row, $index }">
								<el-form-item
									:prop="`target_list.${$index}.old_new_vorder_total`"
									:rules="rules.old_new_vorder_total"
									:show-message="false"
									:inline-message="true"
								>
									<el-input
										v-model.number="row.old_new_vorder_total"
										@blur="
											row.old_new_vorder_total = Number($event.target.value)
										"
										oninput="value=value.replace(/[^\d^\.]/g,'')"
										@input="budgetChange(row)"
									/>
								</el-form-item>
							</template>
						</el-table-column>
						<el-table-column
							label="新客定金数(日)"
							prop="old_new_vorder_day"
							width="130"
							align="center"
						>
							<template slot-scope="{ row, $index }">
								<el-form-item
									:prop="`target_list.${$index}.old_new_vorder_day`"
									:rules="rules.old_new_vorder_day"
									:show-message="false"
									:inline-message="true"
								>
									<el-input
										v-model.number="row.old_new_vorder_day"
										@blur="row.old_new_vorder_day = Number($event.target.value)"
										oninput="value=value.replace(/[^\d^\.]/g,'')"
									/>
								</el-form-item>
							</template>
						</el-table-column>
					</el-table>
				</el-card>
			</el-form-item>
		</el-form>
	</cl-drawer>
</template>
<script>
import dayjs from "dayjs";
import qs from "qs";
import { getTargetRows } from "@/utils";
import { validate } from "@/utils/validate";

export default {
	name: "add-dept-target",
	data() {
		return {
			form: {
				biz_id: "", //事业部
				dept_id: "", // 部门
				dept_ids: [],
				bra_id: "", //品牌
				bra_ids: [],
				company_id: "",
				company_ids: [],
				create_date: dayjs().format("YYYY-MM"),
				target_list: [] // 目标
			},
			rules: {
				biz_id: [{ required: true, message: "请选择事业部" }],
				company_ids: [{ required: true, message: "请选择分公司" }],
				dept_ids: [{ required: true, message: "请选择部门" }],
				bra_ids: [{ required: true, message: "请选择品牌" }],
				create_date: [{ required: true, message: "请选择月份" }],
				vorder_total: [
					{ required: true, message: "请填写加微数(月)" },
					{ validator: validate.targetVal("目标不能为0") }
				],
				vorder_day: [
					{ required: true, message: "请填写加微数(日)" },
					{ validator: validate.targetVal("目标不能为0") }
				],
				old_new_vorder_total: [
					{ required: true, message: "请填写定金数(月)" },
					{ validator: validate.targetVal("目标不能为0") }
				],
				old_new_vorder_day: [
					{ required: true, message: "请填写定金数(日)" },
					{ validator: validate.targetVal("目标不能为0") }
				]
			},
			saving: false,
			deptList: []
		};
	},
	computed: {
		bizRefData() {
			const { biz_id } = this.form;
			return this.getBizRefData(biz_id);
		}
	},
	created() {
		this.form.biz_id = this.getCurrBiz();
	},
	methods: {
		open() {
			this.$refs.drawer.create(() => {
				this.changeBiz();
				this.form.target_list = [];
				this.$nextTick(() => {
					this.reset();
				});
			});
		},
		close() {
			this.reset();
			this.$refs.drawer.close();
		},
		reset() {
			this.saving = false;
			this.$refs.form.resetFields();
		},
		submit() {
			this.$refs.form.validate(async (valid, errors) => {
				this.showFormErr(errors);
				if (!valid) return;
				let { target_list, create_date } = this.form;
				let form = {
					create_date
				};
				target_list.forEach(v => {
					form[`vorder_total${v.uid}`] = v.vorder_total;
					form[`vorder_day${v.uid}`] = v.vorder_day;
					form[`old_new_vorder_total${v.uid}`] = v.old_new_vorder_total;
					form[`old_new_vorder_day${v.uid}`] = v.old_new_vorder_day;
				});
				this.saving = true;
				await this.$service.preSale.adddeptarget(qs.stringify(form)).done(() => {
					this.saving = false;
				});
				this.$message.success("操作成功");
				this.$emit("confirm");
				this.close();
			});
		},
		//事业部切换
		changeBiz() {
			this.form.dept_ids = [];
			this.form.bra_ids = [];
			this.form.company_ids = [];
			this.form.target_list = [];
			this.initChecksData();
			this.setTargetList();
		},
		//分公司
		changeCom() {
			this.form.dept_ids = [];
			this.getDeptList();
			this.setTargetList();
		},
		async initChecksData() {
			const { biz_id } = this.form;
			this.getBizRefBrand(biz_id);
			this.getBizRefCompany(biz_id);
			this.getDeptList();
		},
		async getDeptList() {
			const { biz_id, company_ids } = this.form;
			// this.deptList = (
			// 	(await this.$store.dispatch("common/getDept", {
			// 		parent_id: 0,
			// 		is_store: 0,
			// 		biz_id,
			// 		company_id: company_ids.join(),
			// 		post: 1,
			// 		needAll: false
			// 	})) || []
			// ).map(v => ({ dept_id: v.dept_id, dept_name: v.dept_name }));

			const data = await this.$service.dept.getChildDept({
				biz_id,
				post: 1,
				company_id: company_ids.join(),
				is_store: 0,
				parent_id: 0
			});
			this.deptList = data?.map(v => ({ dept_id: v.dept_id, dept_name: v.dept_name })) || [];
		},
		// 加微数
		quantityTotalChange(row) {
			const { create_date } = this.form;
			if (!row.vorder_total || !create_date) return;
			let days = dayjs(create_date).daysInMonth();
			row.vorder_day = Math.round(row.vorder_total / days);
		},
		// 推广费
		budgetChange(row) {
			const { create_date } = this.form;
			if (!row.old_new_vorder_total || !create_date) return;
			let days = dayjs(create_date).daysInMonth();
			row.old_new_vorder_day = Math.round(row.old_new_vorder_total / days);
		},
		// 生成目标列表
		setTargetList() {
			const { dept_ids, bra_ids, biz_id, company_ids } = this.form;
			const { company: companyData, brand: brandData } = this.bizRefData;
			let bizList = this.business.filter(v => biz_id === v.biz_id);
			let companyList = companyData.filter(v => company_ids.includes(v.company_id));
			let deptList = this.deptList.filter(v => dept_ids.includes(v.dept_id));
			let brandList = brandData.filter(v => bra_ids.includes(v.bra_id));
			let checkList = [bizList, companyList, deptList, brandList];
			let targetList = getTargetRows(checkList).map(v => {
				let item = v.reduce((prev, curr) => ({ ...prev, ...curr }), {
					vorder_total: 0,
					vorder_day: 0,
					old_new_vorder_total: 0,
					old_new_vorder_day: 0
				});
				return {
					...item,
					uid: `[${item.biz_id}][${item.company_id}][${item.dept_id}][0][${item.bra_id}]`
				};
			});
			this.form.target_list = targetList;
		}
	}
};
</script>
<style lang="scss" scoped>
::v-deep {
	.el-table {
		.el-form-item {
			margin-bottom: 0 !important;
		}
	}
	.el-radio-group {
		width: 100%;
	}
}
.row-item {
	margin-bottom: 15px;
}
</style>
